4 * Base class for content handling.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
26 * @author Daniel Kinzler
29 use MediaWiki\Storage\RevisionRecord
;
30 use Wikimedia\Assert\Assert
;
31 use MediaWiki\Logger\LoggerFactory
;
32 use MediaWiki\MediaWikiServices
;
33 use MediaWiki\Revision\SlotRenderingProvider
;
34 use MediaWiki\Search\ParserOutputSearchDataExtractor
;
37 * A content handler knows how do deal with a specific type of content on a wiki
38 * page. Content is stored in the database in a serialized form (using a
39 * serialization format a.k.a. MIME type) and is unserialized into its native
40 * PHP representation (the content model), which is wrapped in an instance of
41 * the appropriate subclass of Content.
43 * ContentHandler instances are stateless singletons that serve, among other
44 * things, as a factory for Content objects. Generally, there is one subclass
45 * of ContentHandler and one subclass of Content for every type of content model.
47 * Some content types have a flat model, that is, their native representation
48 * is the same as their serialized form. Examples would be JavaScript and CSS
49 * code. As of now, this also applies to wikitext (MediaWiki's default content
50 * type), but wikitext content may be represented by a DOM or AST structure in
55 abstract class ContentHandler
{
57 * Convenience function for getting flat text from a Content object. This
58 * should only be used in the context of backwards compatibility with code
59 * that is not yet able to handle Content objects!
61 * If $content is null, this method returns the empty string.
63 * If $content is an instance of TextContent, this method returns the flat
64 * text as returned by $content->getText().
66 * If $content is not a TextContent object, the behavior of this method
67 * depends on the global $wgContentHandlerTextFallback:
68 * - If $wgContentHandlerTextFallback is 'fail' and $content is not a
69 * TextContent object, an MWException is thrown.
70 * - If $wgContentHandlerTextFallback is 'serialize' and $content is not a
71 * TextContent object, $content->serialize() is called to get a string
72 * form of the content.
73 * - If $wgContentHandlerTextFallback is 'ignore' and $content is not a
74 * TextContent object, this method returns null.
75 * - otherwise, the behavior is undefined.
79 * @param Content|null $content
81 * @throws MWException If the content is not an instance of TextContent and
82 * wgContentHandlerTextFallback was set to 'fail'.
83 * @return string|null Textual form of the content, if available.
85 public static function getContentText( Content
$content = null ) {
86 global $wgContentHandlerTextFallback;
88 if ( is_null( $content ) ) {
92 if ( $content instanceof TextContent
) {
93 return $content->getText();
96 wfDebugLog( 'ContentHandler', 'Accessing ' . $content->getModel() . ' content as text!' );
98 if ( $wgContentHandlerTextFallback == 'fail' ) {
99 throw new MWException(
100 "Attempt to get text from Content with model " .
105 if ( $wgContentHandlerTextFallback == 'serialize' ) {
106 return $content->serialize();
113 * Convenience function for creating a Content object from a given textual
116 * $text will be deserialized into a Content object of the model specified
117 * by $modelId (or, if that is not given, $title->getContentModel()) using
122 * @param string $text The textual representation, will be
123 * unserialized to create the Content object
124 * @param Title|null $title The title of the page this text belongs to.
125 * Required if $modelId is not provided.
126 * @param string|null $modelId The model to deserialize to. If not provided,
127 * $title->getContentModel() is used.
128 * @param string|null $format The format to use for deserialization. If not
129 * given, the model's default format is used.
131 * @throws MWException If model ID or format is not supported or if the text can not be
132 * unserialized using the format.
133 * @return Content A Content object representing the text.
135 public static function makeContent( $text, Title
$title = null,
136 $modelId = null, $format = null ) {
137 if ( is_null( $modelId ) ) {
138 if ( is_null( $title ) ) {
139 throw new MWException( "Must provide a Title object or a content model ID." );
142 $modelId = $title->getContentModel();
145 $handler = self
::getForModelID( $modelId );
147 return $handler->unserializeContent( $text, $format );
151 * Returns the name of the default content model to be used for the page
152 * with the given title.
154 * Note: There should rarely be need to call this method directly.
155 * To determine the actual content model for a given page, use
156 * Title::getContentModel().
158 * Which model is to be used by default for the page is determined based
159 * on several factors:
160 * - The global setting $wgNamespaceContentModels specifies a content model
162 * - The hook ContentHandlerDefaultModelFor may be used to override the page's default
164 * - Pages in NS_MEDIAWIKI and NS_USER default to the CSS or JavaScript
165 * model if they end in .js or .css, respectively.
166 * - Pages in NS_MEDIAWIKI default to the wikitext model otherwise.
167 * - The hook TitleIsCssOrJsPage may be used to force a page to use the CSS
168 * or JavaScript model. This is a compatibility feature. The ContentHandlerDefaultModelFor
169 * hook should be used instead if possible.
170 * - The hook TitleIsWikitextPage may be used to force a page to use the
171 * wikitext model. This is a compatibility feature. The ContentHandlerDefaultModelFor
172 * hook should be used instead if possible.
174 * If none of the above applies, the wikitext model is used.
176 * Note: this is used by, and may thus not use, Title::getContentModel()
179 * @deprecated since 1.33, use SlotRoleHandler::getDefaultModel() together with
180 * SlotRoleRegistry::getRoleHandler().
182 * @param Title $title
184 * @return string Default model name for the page given by $title
186 public static function getDefaultModelFor( Title
$title ) {
187 $slotRoleregistry = MediaWikiServices
::getInstance()->getSlotRoleRegistry();
188 $mainSlotHandler = $slotRoleregistry->getRoleHandler( 'main' );
189 return $mainSlotHandler->getDefaultModel( $title );
193 * Returns the appropriate ContentHandler singleton for the given title.
197 * @param Title $title
199 * @return ContentHandler
201 public static function getForTitle( Title
$title ) {
202 $modelId = $title->getContentModel();
204 return self
::getForModelID( $modelId );
208 * Returns the appropriate ContentHandler singleton for the given Content
213 * @param Content $content
215 * @return ContentHandler
217 public static function getForContent( Content
$content ) {
218 $modelId = $content->getModel();
220 return self
::getForModelID( $modelId );
224 * @var array A Cache of ContentHandler instances by model id
226 protected static $handlers;
229 * Returns the ContentHandler singleton for the given model ID. Use the
230 * CONTENT_MODEL_XXX constants to identify the desired content model.
232 * ContentHandler singletons are taken from the global $wgContentHandlers
233 * array. Keys in that array are model names, the values are either
234 * ContentHandler singleton objects, or strings specifying the appropriate
235 * subclass of ContentHandler.
237 * If a class name is encountered when looking up the singleton for a given
238 * model name, the class is instantiated and the class name is replaced by
239 * the resulting singleton in $wgContentHandlers.
241 * If no ContentHandler is defined for the desired $modelId, the
242 * ContentHandler may be provided by the ContentHandlerForModelID hook.
243 * If no ContentHandler can be determined, an MWException is raised.
247 * @param string $modelId The ID of the content model for which to get a
248 * handler. Use CONTENT_MODEL_XXX constants.
250 * @throws MWException For internal errors and problems in the configuration.
251 * @throws MWUnknownContentModelException If no handler is known for the model ID.
252 * @return ContentHandler The ContentHandler singleton for handling the model given by the ID.
254 public static function getForModelID( $modelId ) {
255 global $wgContentHandlers;
257 if ( isset( self
::$handlers[$modelId] ) ) {
258 return self
::$handlers[$modelId];
261 if ( empty( $wgContentHandlers[$modelId] ) ) {
264 Hooks
::run( 'ContentHandlerForModelID', [ $modelId, &$handler ] );
266 if ( $handler === null ) {
267 throw new MWUnknownContentModelException( $modelId );
270 if ( !( $handler instanceof ContentHandler
) ) {
271 throw new MWException( "ContentHandlerForModelID must supply a ContentHandler instance" );
274 $classOrCallback = $wgContentHandlers[$modelId];
276 if ( is_callable( $classOrCallback ) ) {
277 $handler = call_user_func( $classOrCallback, $modelId );
279 $handler = new $classOrCallback( $modelId );
282 if ( !( $handler instanceof ContentHandler
) ) {
283 throw new MWException( "$classOrCallback from \$wgContentHandlers is not " .
284 "compatible with ContentHandler" );
288 wfDebugLog( 'ContentHandler', 'Created handler for ' . $modelId
289 . ': ' . get_class( $handler ) );
291 self
::$handlers[$modelId] = $handler;
293 return self
::$handlers[$modelId];
297 * Clean up handlers cache.
299 public static function cleanupHandlersCache() {
300 self
::$handlers = [];
304 * Returns the localized name for a given content model.
306 * Model names are localized using system messages. Message keys
307 * have the form content-model-$name, where $name is getContentModelName( $id ).
309 * @param string $name The content model ID, as given by a CONTENT_MODEL_XXX
310 * constant or returned by Revision::getContentModel().
311 * @param Language|null $lang The language to parse the message in (since 1.26)
313 * @throws MWException If the model ID isn't known.
314 * @return string The content model's localized name.
316 public static function getLocalizedName( $name, Language
$lang = null ) {
317 // Messages: content-model-wikitext, content-model-text,
318 // content-model-javascript, content-model-css
319 $key = "content-model-$name";
321 $msg = wfMessage( $key );
323 $msg->inLanguage( $lang );
326 return $msg->exists() ?
$msg->plain() : $name;
329 public static function getContentModels() {
330 global $wgContentHandlers;
332 $models = array_keys( $wgContentHandlers );
333 Hooks
::run( 'GetContentModels', [ &$models ] );
337 public static function getAllContentFormats() {
338 global $wgContentHandlers;
342 foreach ( $wgContentHandlers as $model => $class ) {
343 $handler = self
::getForModelID( $model );
344 $formats = array_merge( $formats, $handler->getSupportedFormats() );
347 $formats = array_unique( $formats );
352 // ------------------------------------------------------------------------
362 protected $mSupportedFormats;
365 * Constructor, initializing the ContentHandler instance with its model ID
366 * and a list of supported formats. Values for the parameters are typically
367 * provided as literals by subclass's constructors.
369 * @param string $modelId (use CONTENT_MODEL_XXX constants).
370 * @param string[] $formats List for supported serialization formats
371 * (typically as MIME types)
373 public function __construct( $modelId, $formats ) {
374 $this->mModelID
= $modelId;
375 $this->mSupportedFormats
= $formats;
379 * Serializes a Content object of the type supported by this ContentHandler.
383 * @param Content $content The Content object to serialize
384 * @param string|null $format The desired serialization format
386 * @return string Serialized form of the content
388 abstract public function serializeContent( Content
$content, $format = null );
391 * Applies transformations on export (returns the blob unchanged per default).
392 * Subclasses may override this to perform transformations such as conversion
393 * of legacy formats or filtering of internal meta-data.
395 * @param string $blob The blob to be exported
396 * @param string|null $format The blob's serialization format
400 public function exportTransform( $blob, $format = null ) {
405 * Unserializes a Content object of the type supported by this ContentHandler.
409 * @param string $blob Serialized form of the content
410 * @param string|null $format The format used for serialization
412 * @return Content The Content object created by deserializing $blob
414 abstract public function unserializeContent( $blob, $format = null );
417 * Apply import transformation (per default, returns $blob unchanged).
418 * This gives subclasses an opportunity to transform data blobs on import.
422 * @param string $blob
423 * @param string|null $format
427 public function importTransform( $blob, $format = null ) {
432 * Creates an empty Content object of the type supported by this
439 abstract public function makeEmptyContent();
442 * Creates a new Content object that acts as a redirect to the given page,
443 * or null if redirects are not supported by this content model.
445 * This default implementation always returns null. Subclasses supporting redirects
446 * must override this method.
448 * Note that subclasses that override this method to return a Content object
449 * should also override supportsRedirects() to return true.
453 * @param Title $destination The page to redirect to.
454 * @param string $text Text to include in the redirect, if possible.
456 * @return Content Always null.
458 public function makeRedirectContent( Title
$destination, $text = '' ) {
463 * Returns the model id that identifies the content model this
464 * ContentHandler can handle. Use with the CONTENT_MODEL_XXX constants.
468 * @return string The model ID
470 public function getModelID() {
471 return $this->mModelID
;
477 * @param string $model_id The model to check
479 * @throws MWException If the model ID is not the ID of the content model supported by this
482 protected function checkModelID( $model_id ) {
483 if ( $model_id !== $this->mModelID
) {
484 throw new MWException( "Bad content model: " .
485 "expected {$this->mModelID} " .
486 "but got $model_id." );
491 * Returns a list of serialization formats supported by the
492 * serializeContent() and unserializeContent() methods of this
497 * @return string[] List of serialization formats as MIME type like strings
499 public function getSupportedFormats() {
500 return $this->mSupportedFormats
;
504 * The format used for serialization/deserialization by default by this
507 * This default implementation will return the first element of the array
508 * of formats that was passed to the constructor.
512 * @return string The name of the default serialization format as a MIME type
514 public function getDefaultFormat() {
515 return $this->mSupportedFormats
[0];
519 * Returns true if $format is a serialization format supported by this
520 * ContentHandler, and false otherwise.
522 * Note that if $format is null, this method always returns true, because
523 * null means "use the default format".
527 * @param string $format The serialization format to check
531 public function isSupportedFormat( $format ) {
533 return true; // this means "use the default"
536 return in_array( $format, $this->mSupportedFormats
);
540 * Convenient for checking whether a format provided as a parameter is actually supported.
542 * @param string $format The serialization format to check
544 * @throws MWException If the format is not supported by this content handler.
546 protected function checkFormat( $format ) {
547 if ( !$this->isSupportedFormat( $format ) ) {
548 throw new MWException(
549 "Format $format is not supported for content model "
550 . $this->getModelID()
556 * Returns overrides for action handlers.
557 * Classes listed here will be used instead of the default one when
558 * (and only when) $wgActions[$action] === true. This allows subclasses
559 * to override the default action handlers.
563 * @return array An array mapping action names (typically "view", "edit", "history" etc.) to
564 * either the full qualified class name of an Action class, a callable taking ( Page $page,
565 * IContextSource $context = null ) as parameters and returning an Action object, or an actual
566 * Action object. An empty array in this default implementation.
568 * @see Action::factory
570 public function getActionOverrides() {
575 * Factory for creating an appropriate DifferenceEngine for this content model.
576 * Since 1.32, this is only used for page-level diffs; to diff two content objects,
577 * use getSlotDiffRenderer.
579 * The DifferenceEngine subclass to use is selected in getDiffEngineClass(). The
580 * GetDifferenceEngine hook will receive the DifferenceEngine object and can replace or
582 * (Note that in older versions of MediaWiki the hook documentation instructed extensions
583 * to return false from the hook; you should not rely on always being able to decorate
584 * the DifferenceEngine instance from the hook. If the owner of the content type wants to
585 * decorare the instance, overriding this method is a safer approach.)
587 * @todo This is page-level functionality so it should not belong to ContentHandler.
588 * Move it to a better place once one exists (e.g. PageTypeHandler).
592 * @param IContextSource $context Context to use, anything else will be ignored.
593 * @param int $old Revision ID we want to show and diff with.
594 * @param int|string $new Either a revision ID or one of the strings 'cur', 'prev' or 'next'.
595 * @param int $rcid FIXME: Deprecated, no longer used. Defaults to 0.
596 * @param bool $refreshCache If set, refreshes the diff cache. Defaults to false.
597 * @param bool $unhide If set, allow viewing deleted revs. Defaults to false.
599 * @return DifferenceEngine
601 public function createDifferenceEngine( IContextSource
$context, $old = 0, $new = 0,
602 $rcid = 0, // FIXME: Deprecated, no longer used
603 $refreshCache = false, $unhide = false
605 $diffEngineClass = $this->getDiffEngineClass();
606 $differenceEngine = new $diffEngineClass( $context, $old, $new, $rcid, $refreshCache, $unhide );
607 Hooks
::run( 'GetDifferenceEngine', [ $context, $old, $new, $refreshCache, $unhide,
608 &$differenceEngine ] );
609 return $differenceEngine;
613 * Get an appropriate SlotDiffRenderer for this content model.
615 * @param IContextSource $context
616 * @return SlotDiffRenderer
618 final public function getSlotDiffRenderer( IContextSource
$context ) {
619 $slotDiffRenderer = $this->getSlotDiffRendererInternal( $context );
620 if ( get_class( $slotDiffRenderer ) === TextSlotDiffRenderer
::class ) {
621 // To keep B/C, when SlotDiffRenderer is not overridden for a given content type
622 // but DifferenceEngine is, use that instead.
623 $differenceEngine = $this->createDifferenceEngine( $context );
624 if ( get_class( $differenceEngine ) !== DifferenceEngine
::class ) {
625 // TODO turn this into a deprecation warning in a later release
626 LoggerFactory
::getInstance( 'diff' )->info(
627 'Falling back to DifferenceEngineSlotDiffRenderer', [
628 'modelID' => $this->getModelID(),
629 'DifferenceEngine' => get_class( $differenceEngine ),
631 $slotDiffRenderer = new DifferenceEngineSlotDiffRenderer( $differenceEngine );
634 Hooks
::run( 'GetSlotDiffRenderer', [ $this, &$slotDiffRenderer, $context ] );
635 return $slotDiffRenderer;
639 * Return the SlotDiffRenderer appropriate for this content handler.
640 * @param IContextSource $context
641 * @return SlotDiffRenderer
643 protected function getSlotDiffRendererInternal( IContextSource
$context ) {
644 $contentLanguage = MediaWikiServices
::getInstance()->getContentLanguage();
645 $statsdDataFactory = MediaWikiServices
::getInstance()->getStatsdDataFactory();
646 $slotDiffRenderer = new TextSlotDiffRenderer();
647 $slotDiffRenderer->setStatsdDataFactory( $statsdDataFactory );
648 // XXX using the page language would be better, but it's unclear how that should be injected
649 $slotDiffRenderer->setLanguage( $contentLanguage );
651 $engine = DifferenceEngine
::getEngine();
652 if ( $engine === false ) {
653 $slotDiffRenderer->setEngine( TextSlotDiffRenderer
::ENGINE_PHP
);
654 } elseif ( $engine === 'wikidiff2' ) {
655 $slotDiffRenderer->setEngine( TextSlotDiffRenderer
::ENGINE_WIKIDIFF2
);
657 $slotDiffRenderer->setEngine( TextSlotDiffRenderer
::ENGINE_EXTERNAL
, $engine );
660 return $slotDiffRenderer;
664 * Get the language in which the content of the given page is written.
666 * This default implementation just returns the content language (except for pages
667 * in the MediaWiki namespace)
669 * Note that the page's language is not cacheable, since it may in some
670 * cases depend on user settings.
672 * Also note that the page language may or may not depend on the actual content of the page,
673 * that is, this method may load the content in order to determine the language.
677 * @param Title $title The page to determine the language for.
678 * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
680 * @return Language The page's language
682 public function getPageLanguage( Title
$title, Content
$content = null ) {
684 $pageLang = MediaWikiServices
::getInstance()->getContentLanguage();
686 if ( $title->inNamespace( NS_MEDIAWIKI
) ) {
687 // Parse mediawiki messages with correct target language
688 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $title->getText() );
689 $pageLang = Language
::factory( $lang );
692 // Simplify hook handlers by only passing objects of one type, in case nothing
693 // else has unstubbed the StubUserLang object by now.
694 StubObject
::unstub( $wgLang );
696 Hooks
::run( 'PageContentLanguage', [ $title, &$pageLang, $wgLang ] );
698 return wfGetLangObj( $pageLang );
702 * Get the language in which the content of this page is written when
703 * viewed by user. Defaults to $this->getPageLanguage(), but if the user
704 * specified a preferred variant, the variant will be used.
706 * This default implementation just returns $this->getPageLanguage( $title, $content ) unless
707 * the user specified a preferred variant.
709 * Note that the pages view language is not cacheable, since it depends on user settings.
711 * Also note that the page language may or may not depend on the actual content of the page,
712 * that is, this method may load the content in order to determine the language.
716 * @param Title $title The page to determine the language for.
717 * @param Content|null $content The page's content, if you have it handy, to avoid reloading it.
719 * @return Language The page's language for viewing
721 public function getPageViewLanguage( Title
$title, Content
$content = null ) {
722 $pageLang = $this->getPageLanguage( $title, $content );
724 if ( $title->getNamespace() !== NS_MEDIAWIKI
) {
725 // If the user chooses a variant, the content is actually
726 // in a language whose code is the variant code.
727 $variant = $pageLang->getPreferredVariant();
728 if ( $pageLang->getCode() !== $variant ) {
729 $pageLang = Language
::factory( $variant );
737 * Determines whether the content type handled by this ContentHandler
738 * can be used for the main slot of the given page.
740 * This default implementation always returns true.
741 * Subclasses may override this to restrict the use of this content model to specific locations,
742 * typically based on the namespace or some other aspect of the title, such as a special suffix
743 * (e.g. ".svg" for SVG content).
745 * @note this calls the ContentHandlerCanBeUsedOn hook which may be used to override which
746 * content model can be used where.
748 * @see SlotRoleHandler::isAllowedModel
750 * @param Title $title The page's title.
752 * @return bool True if content of this kind can be used on the given page, false otherwise.
754 public function canBeUsedOn( Title
$title ) {
757 Hooks
::run( 'ContentModelCanBeUsedOn', [ $this->getModelID(), $title, &$ok ] );
763 * Returns the name of the diff engine to use.
769 protected function getDiffEngineClass() {
770 return DifferenceEngine
::class;
774 * Attempts to merge differences between three versions. Returns a new
775 * Content object for a clean merge and false for failure or a conflict.
777 * This default implementation always returns false.
781 * @param Content $oldContent The page's previous content.
782 * @param Content $myContent One of the page's conflicting contents.
783 * @param Content $yourContent One of the page's conflicting contents.
785 * @return Content|bool Always false.
787 public function merge3( Content
$oldContent, Content
$myContent, Content
$yourContent ) {
792 * Return type of change if one exists for the given edit.
796 * @param Content|null $oldContent The previous text of the page.
797 * @param Content|null $newContent The submitted text of the page.
798 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
800 * @return string|null String key representing type of change, or null.
802 private function getChangeType(
803 Content
$oldContent = null,
804 Content
$newContent = null,
807 $oldTarget = $oldContent !== null ?
$oldContent->getRedirectTarget() : null;
808 $newTarget = $newContent !== null ?
$newContent->getRedirectTarget() : null;
810 // We check for the type of change in the given edit, and return string key accordingly
812 // Blanking of a page
813 if ( $oldContent && $oldContent->getSize() > 0 &&
814 $newContent && $newContent->getSize() === 0
822 // New redirect page (by creating new page or by changing content page)
823 return 'new-redirect';
824 } elseif ( !$newTarget->equals( $oldTarget ) ||
825 $oldTarget->getFragment() !== $newTarget->getFragment()
827 // Redirect target changed
828 return 'changed-redirect-target';
830 } elseif ( $oldTarget ) {
831 // Changing an existing redirect into a non-redirect
832 return 'removed-redirect';
836 if ( $flags & EDIT_NEW
&& $newContent ) {
837 if ( $newContent->getSize() === 0 ) {
845 // Removing more than 90% of the page
846 if ( $oldContent && $newContent && $oldContent->getSize() > 10 * $newContent->getSize() ) {
850 // Content model changed
851 if ( $oldContent && $newContent && $oldContent->getModel() !== $newContent->getModel() ) {
852 return 'contentmodelchange';
859 * Return an applicable auto-summary if one exists for the given edit.
863 * @param Content|null $oldContent The previous text of the page.
864 * @param Content|null $newContent The submitted text of the page.
865 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
867 * @return string An appropriate auto-summary, or an empty string.
869 public function getAutosummary(
870 Content
$oldContent = null,
871 Content
$newContent = null,
874 $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
876 // There's no applicable auto-summary for our case, so our auto-summary is empty.
877 if ( !$changeType ) {
881 // Decide what kind of auto-summary is needed.
882 switch ( $changeType ) {
884 $newTarget = $newContent->getRedirectTarget();
885 $truncatedtext = $newContent->getTextForSummary(
887 - strlen( wfMessage( 'autoredircomment' )->inContentLanguage()->text() )
888 - strlen( $newTarget->getFullText() )
891 return wfMessage( 'autoredircomment', $newTarget->getFullText() )
892 ->plaintextParams( $truncatedtext )->inContentLanguage()->text();
893 case 'changed-redirect-target':
894 $oldTarget = $oldContent->getRedirectTarget();
895 $newTarget = $newContent->getRedirectTarget();
897 $truncatedtext = $newContent->getTextForSummary(
899 - strlen( wfMessage( 'autosumm-changed-redirect-target' )
900 ->inContentLanguage()->text() )
901 - strlen( $oldTarget->getFullText() )
902 - strlen( $newTarget->getFullText() )
905 return wfMessage( 'autosumm-changed-redirect-target',
906 $oldTarget->getFullText(),
907 $newTarget->getFullText() )
908 ->rawParams( $truncatedtext )->inContentLanguage()->text();
909 case 'removed-redirect':
910 $oldTarget = $oldContent->getRedirectTarget();
911 $truncatedtext = $newContent->getTextForSummary(
913 - strlen( wfMessage( 'autosumm-removed-redirect' )
914 ->inContentLanguage()->text() )
915 - strlen( $oldTarget->getFullText() ) );
917 return wfMessage( 'autosumm-removed-redirect', $oldTarget->getFullText() )
918 ->rawParams( $truncatedtext )->inContentLanguage()->text();
920 // If they're making a new article, give its text, truncated, in the summary.
921 $truncatedtext = $newContent->getTextForSummary(
922 200 - strlen( wfMessage( 'autosumm-new' )->inContentLanguage()->text() ) );
924 return wfMessage( 'autosumm-new' )->rawParams( $truncatedtext )
925 ->inContentLanguage()->text();
927 return wfMessage( 'autosumm-blank' )->inContentLanguage()->text();
929 $truncatedtext = $newContent->getTextForSummary(
930 200 - strlen( wfMessage( 'autosumm-replace' )->inContentLanguage()->text() ) );
932 return wfMessage( 'autosumm-replace' )->rawParams( $truncatedtext )
933 ->inContentLanguage()->text();
935 return wfMessage( 'autosumm-newblank' )->inContentLanguage()->text();
942 * Return an applicable tag if one exists for the given edit or return null.
946 * @param Content|null $oldContent The previous text of the page.
947 * @param Content|null $newContent The submitted text of the page.
948 * @param int $flags Bit mask: a bit mask of flags submitted for the edit.
950 * @return string|null An appropriate tag, or null.
952 public function getChangeTag(
953 Content
$oldContent = null,
954 Content
$newContent = null,
957 $changeType = $this->getChangeType( $oldContent, $newContent, $flags );
959 // There's no applicable tag for this change.
960 if ( !$changeType ) {
964 // Core tags use the same keys as ones returned from $this->getChangeType()
965 // but prefixed with pseudo namespace 'mw-', so we add the prefix before checking
966 // if this type of change should be tagged
967 $tag = 'mw-' . $changeType;
969 // Not all change types are tagged, so we check against the list of defined tags.
970 if ( in_array( $tag, ChangeTags
::getSoftwareTags() ) ) {
978 * Auto-generates a deletion reason
982 * @param Title $title The page's title
983 * @param bool &$hasHistory Whether the page has a history
985 * @return mixed String containing deletion reason or empty string, or
986 * boolean false if no revision occurred
988 * @todo &$hasHistory is extremely ugly, it's here because
989 * WikiPage::getAutoDeleteReason() and Article::generateReason()
992 public function getAutoDeleteReason( Title
$title, &$hasHistory ) {
993 $dbr = wfGetDB( DB_REPLICA
);
995 // Get the last revision
996 $rev = Revision
::newFromTitle( $title );
998 if ( is_null( $rev ) ) {
1002 // Get the article's contents
1003 $content = $rev->getContent();
1006 // If the page is blank, use the text from the previous revision,
1007 // which can only be blank if there's a move/import/protect dummy
1008 // revision involved
1009 if ( !$content ||
$content->isEmpty() ) {
1010 $prev = $rev->getPrevious();
1014 $content = $rev->getContent();
1019 $this->checkModelID( $rev->getContentModel() );
1021 // Find out if there was only one contributor
1022 // Only scan the last 20 revisions
1023 $revQuery = Revision
::getQueryInfo();
1024 $res = $dbr->select(
1025 $revQuery['tables'],
1026 [ 'rev_user_text' => $revQuery['fields']['rev_user_text'] ],
1028 'rev_page' => $title->getArticleID(),
1029 $dbr->bitAnd( 'rev_deleted', RevisionRecord
::DELETED_USER
) . ' = 0'
1036 if ( $res === false ) {
1037 // This page has no revisions, which is very weird
1041 $hasHistory = ( $res->numRows() > 1 );
1042 $row = $dbr->fetchObject( $res );
1044 if ( $row ) { // $row is false if the only contributor is hidden
1045 $onlyAuthor = $row->rev_user_text
;
1046 // Try to find a second contributor
1047 foreach ( $res as $row ) {
1048 if ( $row->rev_user_text
!= $onlyAuthor ) { // T24999
1049 $onlyAuthor = false;
1054 $onlyAuthor = false;
1057 // Generate the summary with a '$1' placeholder
1059 // The current revision is blank and the one before is also
1060 // blank. It's just not our lucky day
1061 $reason = wfMessage( 'exbeforeblank', '$1' )->inContentLanguage()->text();
1063 if ( $onlyAuthor ) {
1064 $reason = wfMessage(
1068 )->inContentLanguage()->text();
1070 $reason = wfMessage( 'excontent', '$1' )->inContentLanguage()->text();
1074 if ( $reason == '-' ) {
1075 // Allow these UI messages to be blanked out cleanly
1079 // Max content length = max comment length - length of the comment (excl. $1)
1080 $maxLength = CommentStore
::COMMENT_CHARACTER_LIMIT
- ( strlen( $reason ) - 2 );
1081 $text = $content ?
$content->getTextForSummary( $maxLength ) : '';
1083 // Now replace the '$1' placeholder
1084 $reason = str_replace( '$1', $text, $reason );
1090 * Get the Content object that needs to be saved in order to undo all revisions
1091 * between $undo and $undoafter. Revisions must belong to the same page,
1092 * must exist and must not be deleted.
1095 * @since 1.32 accepts Content objects for all parameters instead of Revision objects.
1096 * Passing Revision objects is deprecated.
1098 * @param Revision|Content $current The current text
1099 * @param Revision|Content $undo The content of the revision to undo
1100 * @param Revision|Content $undoafter Must be from an earlier revision than $undo
1101 * @param bool $undoIsLatest Set true if $undo is from the current revision (since 1.32)
1103 * @return mixed Content on success, false on failure
1105 public function getUndoContent( $current, $undo, $undoafter, $undoIsLatest = false ) {
1106 Assert
::parameterType( Revision
::class . '|' . Content
::class, $current, '$current' );
1107 if ( $current instanceof Content
) {
1108 Assert
::parameter( $undo instanceof Content
, '$undo',
1109 'Must be Content when $current is Content' );
1110 Assert
::parameter( $undoafter instanceof Content
, '$undoafter',
1111 'Must be Content when $current is Content' );
1112 $cur_content = $current;
1113 $undo_content = $undo;
1114 $undoafter_content = $undoafter;
1116 Assert
::parameter( $undo instanceof Revision
, '$undo',
1117 'Must be Revision when $current is Revision' );
1118 Assert
::parameter( $undoafter instanceof Revision
, '$undoafter',
1119 'Must be Revision when $current is Revision' );
1121 $cur_content = $current->getContent();
1123 if ( empty( $cur_content ) ) {
1124 return false; // no page
1127 $undo_content = $undo->getContent();
1128 $undoafter_content = $undoafter->getContent();
1130 if ( !$undo_content ||
!$undoafter_content ) {
1131 return false; // no content to undo
1134 $undoIsLatest = $current->getId() === $undo->getId();
1138 $this->checkModelID( $cur_content->getModel() );
1139 $this->checkModelID( $undo_content->getModel() );
1140 if ( !$undoIsLatest ) {
1141 // If we are undoing the most recent revision,
1142 // its ok to revert content model changes. However
1143 // if we are undoing a revision in the middle, then
1144 // doing that will be confusing.
1145 $this->checkModelID( $undoafter_content->getModel() );
1147 } catch ( MWException
$e ) {
1148 // If the revisions have different content models
1149 // just return false
1153 if ( $cur_content->equals( $undo_content ) ) {
1154 // No use doing a merge if it's just a straight revert.
1155 return $undoafter_content;
1158 $undone_content = $this->merge3( $undo_content, $undoafter_content, $cur_content );
1160 return $undone_content;
1164 * Get parser options suitable for rendering and caching the article
1166 * @deprecated since 1.32, use WikiPage::makeParserOptions() or
1167 * ParserOptions::newCanonical() instead.
1168 * @param IContextSource|User|string $context One of the following:
1169 * - IContextSource: Use the User and the Language of the provided
1171 * - User: Use the provided User object and $wgLang for the language,
1172 * so use an IContextSource object if possible.
1173 * - 'canonical': Canonical options (anonymous user with default
1174 * preferences and content language).
1176 * @throws MWException
1177 * @return ParserOptions
1179 public function makeParserOptions( $context ) {
1180 wfDeprecated( __METHOD__
, '1.32' );
1181 return ParserOptions
::newCanonical( $context );
1185 * Returns true for content models that support caching using the
1186 * ParserCache mechanism. See WikiPage::shouldCheckParserCache().
1190 * @return bool Always false.
1192 public function isParserCacheSupported() {
1197 * Returns true if this content model supports sections.
1198 * This default implementation returns false.
1200 * Content models that return true here should also implement
1201 * Content::getSection, Content::replaceSection, etc. to handle sections..
1203 * @return bool Always false.
1205 public function supportsSections() {
1210 * Returns true if this content model supports categories.
1211 * The default implementation returns true.
1213 * @return bool Always true.
1215 public function supportsCategories() {
1220 * Returns true if this content model supports redirects.
1221 * This default implementation returns false.
1223 * Content models that return true here should also implement
1224 * ContentHandler::makeRedirectContent to return a Content object.
1226 * @return bool Always false.
1228 public function supportsRedirects() {
1233 * Return true if this content model supports direct editing, such as via EditPage.
1235 * @return bool Default is false, and true for TextContent and it's derivatives.
1237 public function supportsDirectEditing() {
1242 * Whether or not this content model supports direct editing via ApiEditPage
1244 * @return bool Default is false, and true for TextContent and derivatives.
1246 public function supportsDirectApiEditing() {
1247 return $this->supportsDirectEditing();
1251 * Get fields definition for search index
1253 * @todo Expose title, redirect, namespace, text, source_text, text_bytes
1254 * field mappings here. (see T142670 and T143409)
1256 * @param SearchEngine $engine
1257 * @return SearchIndexField[] List of fields this content handler can provide.
1260 public function getFieldsForSearchIndex( SearchEngine
$engine ) {
1261 $fields['category'] = $engine->makeSearchFieldMapping(
1263 SearchIndexField
::INDEX_TYPE_TEXT
1265 $fields['category']->setFlag( SearchIndexField
::FLAG_CASEFOLD
);
1267 $fields['external_link'] = $engine->makeSearchFieldMapping(
1269 SearchIndexField
::INDEX_TYPE_KEYWORD
1272 $fields['outgoing_link'] = $engine->makeSearchFieldMapping(
1274 SearchIndexField
::INDEX_TYPE_KEYWORD
1277 $fields['template'] = $engine->makeSearchFieldMapping(
1279 SearchIndexField
::INDEX_TYPE_KEYWORD
1281 $fields['template']->setFlag( SearchIndexField
::FLAG_CASEFOLD
);
1283 $fields['content_model'] = $engine->makeSearchFieldMapping(
1285 SearchIndexField
::INDEX_TYPE_KEYWORD
1292 * Add new field definition to array.
1293 * @param SearchIndexField[] &$fields
1294 * @param SearchEngine $engine
1295 * @param string $name
1297 * @return SearchIndexField[] new field defs
1300 protected function addSearchField( &$fields, SearchEngine
$engine, $name, $type ) {
1301 $fields[$name] = $engine->makeSearchFieldMapping( $name, $type );
1306 * Return fields to be indexed by search engine
1307 * as representation of this document.
1308 * Overriding class should call parent function or take care of calling
1309 * the SearchDataForIndex hook.
1310 * @param WikiPage $page Page to index
1311 * @param ParserOutput $output
1312 * @param SearchEngine $engine Search engine for which we are indexing
1313 * @return array Map of name=>value for fields
1316 public function getDataForSearchIndex(
1318 ParserOutput
$output,
1319 SearchEngine
$engine
1322 $content = $page->getContent();
1325 $searchDataExtractor = new ParserOutputSearchDataExtractor();
1327 $fieldData['category'] = $searchDataExtractor->getCategories( $output );
1328 $fieldData['external_link'] = $searchDataExtractor->getExternalLinks( $output );
1329 $fieldData['outgoing_link'] = $searchDataExtractor->getOutgoingLinks( $output );
1330 $fieldData['template'] = $searchDataExtractor->getTemplates( $output );
1332 $text = $content->getTextForSearchIndex();
1334 $fieldData['text'] = $text;
1335 $fieldData['source_text'] = $text;
1336 $fieldData['text_bytes'] = $content->getSize();
1337 $fieldData['content_model'] = $content->getModel();
1340 Hooks
::run( 'SearchDataForIndex', [ &$fieldData, $this, $page, $output, $engine ] );
1345 * Produce page output suitable for indexing.
1347 * Specific content handlers may override it if they need different content handling.
1349 * @param WikiPage $page
1350 * @param ParserCache|null $cache
1351 * @return ParserOutput
1353 public function getParserOutputForIndexing( WikiPage
$page, ParserCache
$cache = null ) {
1354 // TODO: MCR: ContentHandler should be called per slot, not for the whole page.
1356 $parserOptions = $page->makeParserOptions( 'canonical' );
1358 $parserOutput = $cache->get( $page, $parserOptions );
1361 if ( empty( $parserOutput ) ) {
1362 $renderer = MediaWikiServices
::getInstance()->getRevisionRenderer();
1364 $renderer->getRenderedRevision(
1365 $page->getRevision()->getRevisionRecord(),
1367 )->getRevisionParserOutput();
1369 $cache->save( $parserOutput, $page, $parserOptions );
1372 return $parserOutput;
1376 * Returns a list of DeferrableUpdate objects for recording information about the
1377 * given Content in some secondary data store.
1379 * Application logic should not call this method directly. Instead, it should call
1380 * DerivedPageDataUpdater::getSecondaryDataUpdates().
1382 * @note Implementations must not return a LinksUpdate instance. Instead, a LinksUpdate
1383 * is created by the calling code in DerivedPageDataUpdater, on the combined ParserOutput
1384 * of all slots, not for each slot individually. This is in contrast to the old
1385 * getSecondaryDataUpdates method defined by AbstractContent, which returned a LinksUpdate.
1387 * @note Implementations should not call $content->getParserOutput, they should call
1388 * $slotOutput->getSlotRendering( $role, false ) instead if they need to access a ParserOutput
1389 * of $content. This allows existing ParserOutput objects to be re-used, while avoiding
1390 * creating a ParserOutput when none is needed.
1392 * @param Title $title The title of the page to supply the updates for
1393 * @param Content $content The content to generate data updates for.
1394 * @param string $role The role (slot) in which the content is being used. Which updates
1395 * are performed should generally not depend on the role the content has, but the
1396 * DeferrableUpdates themselves may need to know the role, to track to which slot the
1397 * data refers, and to avoid overwriting data of the same kind from another slot.
1398 * @param SlotRenderingProvider $slotOutput A provider that can be used to gain access to
1399 * a ParserOutput of $content by calling $slotOutput->getSlotParserOutput( $role, false ).
1400 * @return DeferrableUpdate[] A list of DeferrableUpdate objects for putting information
1401 * about this content object somewhere. The default implementation returns an empty
1405 public function getSecondaryDataUpdates(
1409 SlotRenderingProvider
$slotOutput
1415 * Returns a list of DeferrableUpdate objects for removing information about content
1416 * in some secondary data store. This is used when a page is deleted, and also when
1417 * a slot is removed from a page.
1419 * Application logic should not call this method directly. Instead, it should call
1420 * WikiPage::getSecondaryDataUpdates().
1422 * @note Implementations must not return a LinksDeletionUpdate instance. Instead, a
1423 * LinksDeletionUpdate is created by the calling code in WikiPage.
1424 * This is in contrast to the old getDeletionUpdates method defined by AbstractContent,
1425 * which returned a LinksUpdate.
1427 * @note Implementations should not rely on the page's current content, but rather the current
1428 * state of the secondary data store.
1430 * @param Title $title The title of the page to supply the updates for
1431 * @param string $role The role (slot) in which the content is being used. Which updates
1432 * are performed should generally not depend on the role the content has, but the
1433 * DeferrableUpdates themselves may need to know the role, to track to which slot the
1434 * data refers, and to avoid overwriting data of the same kind from another slot.
1436 * @return DeferrableUpdate[] A list of DeferrableUpdate objects for putting information
1437 * about this content object somewhere. The default implementation returns an empty
1442 public function getDeletionUpdates( Title
$title, $role ) {